<template>
  <div>
    <el-divider content-position="left">新增系统用户</el-divider>
    <el-form :model="form" ref="form" :rules="rules">
      <el-form-item label="选择用户:">
        <el-select @change="userSelect" v-model="name" style="width: 400px">
          <el-option
            v-for="item in userArray"
            :key="item.name"
            :label="item.name"
            :value="item.name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="用户头像" prop="pic">
        <el-upload
          v-model="form.pic"
          class="avatar-uploader"
          :action="`${UPLOADURL}/upload`"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.pic" :src="form.pic" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="注册账号:" prop="username">
        <el-input
          @change="nameChangeFn"
          v-model="form.username"
          placeholder="请输入6-12位用户账号"
          style="width: 400px"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input
          @change="nameChangeFn2"
          v-model="form.password"
          type="password"
          show-password
          placeholder="请输入6-13位数密码"
          style="width: 400px"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码:" prop="repassword">
        <el-input
          @change="nameChangeFn3"
          show-password
          v-model="form.repassword"
          type="password"
          placeholder="请再次确认密码"
          style="width: 400px"
        ></el-input>
      </el-form-item>
      <el-form-item label="用户级别:" prop="level">
        <el-select
          style="width: 400px"
          @change="regionChangeFn"
          v-model="form.level"
        >
          <el-option
            v-for="item in levelList"
            :key="item.sname"
            :label="item.sname"
            :value="item.sname"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="进度条:">
        <el-progress
          style="width: 500px"
          :text-inside="true"
          :stroke-width="26"
          :percentage="percentage"
        ></el-progress>
      </el-form-item>
      <el-form-item>
        <el-button style="margin-left: 180px" type="success" @click="submit"
          >提交</el-button
        >
        <el-button type="warning" plain @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import httpApi from "@/http";
export default {
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.password) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      userArray: [],
      levelList: [],
      name: "",
      percentage: 0,
      form: {
        username: "",
        password: "",
        repassword: "",
        pic: "",
        level: "",
      },
      calculateIntegrityForm: {
        username: 0,
        password: 0,
        repassword: 0,
        level: 0,
      },
      rules: {
        username: [
          { required: true, message: "请填写用户名", trigger: "blur" },
          {
            pattern: /^\w{6,12}$/,
            message: "6~12位字符，可以包含：数字、字母、下划线",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请填写密码", trigger: "blur" },
          {
            pattern: /^\w{6,13}$/,
            message: "6~13位字符，可以包含：数字、字母、下划线",
            trigger: "blur",
          },
        ],
        repassword: [
          { required: true, validator: validatePass2, trigger: "blur" },
        ],
        level: [{ required: true, message: "必填", trigger: "blur" }],
      },
    };
  },
  methods: {
    isEmpty(str) {
      let thisType = typeof str;
      if (str === "" || str === null || str === undefined) {
        // null、undefined
        // 这里之所以用全等于，因为：
        // 1.JS里，‘' == 0 == [],会被判断成相同，而下方针对数字0和空数组做出单独处理，故此处只需要单独判断‘'
        // 2.JS里，typeof null == object,为简化下方object处判断逻辑，故此处需要用全等判断null
        return true;
      } else if (
        thisType == "string" &&
        str.replace(/(^\s*)|(\s*$)/g, "").length == 0
      ) {
        //string
        return true;
      } else if ((thisType == "number" && isNaN(str)) || str == 0) {
        //number
        return true;
      } else if (thisType == "object") {
        if (str instanceof Array) {
          // 数组为空判断
          return str.length == 0;
        } else {
          // 对象为空判断
          return JSON.stringify(str) == "{}";
        }
      }
      return false; // 传入str不为空
    },
    updateProgress(key, num) {
      let sum = 0;
      if (this.isEmpty(this.form[key])) {
        // 监听的元素为空
        this.calculateIntegrityForm[key] = 0;
      } else {
        // 监听的元素不为空
        this.calculateIntegrityForm[key] = num;
      }
      for (let i in this.calculateIntegrityForm) {
        sum += this.calculateIntegrityForm[i];
      }
      this.percentage = sum;
    },
    regionChangeFn(val) {
      this.form.level = val;
      this.updateProgress("level", 25);
    },
    nameChangeFn(val) {
      this.form.username = val;
      this.updateProgress("username", 25);
    },
    nameChangeFn2(val) {
      this.form.password = val;
      this.updateProgress("password", 25);
    },
    nameChangeFn3(val) {
      this.form.repassword = val;
      this.updateProgress("repassword", 25);
    },
    userList() {
      httpApi.systemApi.queryUser().then((res) => {
        this.userArray = res.data.data;
      });
    },
    userSelect() {
      httpApi.systemApi.queryPic({ name: this.name }).then((res) => {
        console.log(res);
        this.form.pic = res.data.data[0].pic;
      });
    },
    queryLevelList() {
      httpApi.systemApi.queryLevel().then((res) => {
        this.levelList = res.data.data;
      });
    },
    reset() {
      this.$refs.form.resetFields();
    },
    handleAvatarSuccess(res, file) {
      this.form.pic = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          let params = {
            username: this.form.username,
            password: this.form.password,
            pic: this.form.pic,
            level: this.form.level,
          };
          console.log(params);
          httpApi.systemApi.register(params).then((res) => {
            console.log(res);
            if (res.data.code == 200) {
              this.$message({ type: "success", message: "注册成功" });
              setTimeout(() => {
                this.$router.go(0);
              }, 1000);
            } else {
              this.$message({ type: "error", message: res.data.msg });
            }
          });
        }
      });
    },
  },
  mounted() {
    this.userList();
    this.queryLevelList();
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__label {
  width: 100px;
  text-align-last: justify;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  border: 1px dashed #dcdfe6;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>